<?php
/**
 * 接口控制器
 */
namespace Admin\Controller;
use Think\Controller;
use Think\Log;
use Org\Util\Page;
class ApprovalController extends BaseController
{
	public function index(){
       //echo   date('Y-m-d H:i:s',strtotime("-8 hours"));
        $this->display();
    }


    public function ApprovalList()
    {
  
    $_listrows = I('request.verypageshowcount', '', 'trim');

        $keywords = I('request.keywords','','trim');
        if(!empty($keywords)){
            $_where['purchaseame|linkname|goodsname|goodsid']=array('like',"%{$keywords}%");
        }
        
        $start_time = I('request.start_time','','trim');
        $end_time = I('request.end_time','','trim');
        $str='';
        //如果两个为空，没有条件
        //否则 一个为空，一个有值，两个有值 
        if(!(empty($start_time) && empty($end_time))){ 
            $start_time = empty($start_time)?date("Y-m-d H:i:s"):$start_time;
            $end_time = empty($end_time)?date("Y-m-d H:i:s"):$end_time;
            
            if($start_time>$end_time){
                 $temp=$end_time;
                 $end_time=$start_time;
                 $start_time=$temp;
            }  

          $str =" and a.createtime between '".$start_time." 00:00:01' and '".$end_time." 23:59:59'"; 
          
        }  
        $str.=" and a.ishandle = 0";
        $str.=" and a.check = '0'";
        $str = ltrim(trim($str),'and');
        if(!empty($str)){
            $_where['_string']=$str;
        }
        //未审核的报价单
         
        $where_order['where'] = $_where;
        /*$where_order['order'] = ' last_transaction_time desc ';*/
        $where_order['listrows'] = $_listrows;
        $where_order["id"]="load_tb_div";
        $where_order["field"]="a.*,b.offer_number,b.actual_number,b.offer_price,b.sendtime,b.isbatch,b.iscomfirm,c.purchaseame,d.linkname,e.goodsname,e.goodsid";
        $where_order['alias']="a";
        $where_order['order'] = "createtime DESC";
        $where_order["join"] =array('left join '.$this->dbprefix.'wx_offerlist b on a.offerid=b.offerid',' left join '.$this->dbprefix.'wx_purchase c on a.purchaseid=c.purchaseid',' left join '.$this->dbprefix.'wx_supplier d on a.sp_id=d.sp_id',' left join '.$this->dbprefix.'wx_purchaselist e on b.listid=e.listid');
        $_datalist = $this->_getListsFromModel('wx_offer', $where_order);
        $Arr = array('默认','交易成功','验证发票','等收发票','交易失败','等待收货','验证失败');
        $Arr2 =array('提交','有效','部分有效');
        $this->assign('arr',$Arr);
        $this->assign('arr2',$Arr2);
        $this->assign('_datalist', $_datalist);
        $this->display(); 

    }

    public function add_purchase(){
       $this->display();
    }

    public function addPurchase(){

        $data['purchaseid'] = guid() ;
       $data['purchaseame'] =I('post.username');
       $data['lasttime'] =I('post.end_time');
       $data['remark'] =I('post.remark');
       $data['isactive'] =I('post.in_or_out');
       $data['operationuser'] = $_SESSION['admin_id'];
       $data['createtime'] = date('Y-m-d H:i:s');
       $exe_scriptstr = "<script>
        setTimeout(function(){
            var win=    art.dialog.opener;
                        win._reload_currentpage_datalist('load_tb_div');
                        art.dialog.close();
        },500);
       </script>";

       $res = D('wx_purchase')->add($data);

       if($res != false){
            //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
            $this->success('操作成功！' . $exe_scriptstr);
       }else{


           $this->success('操作失败！' . $exe_scriptstr);
       }
        $this->display();


}

    public function update_wx_purchase(){
        $map['purchaseid'] = I('get.purchaseid');
       $list = D('wx_purchase')->where($map)->find();

       if($list != flase){
        $this->assign('list',$list);
        $this->display();
       }
    }

    public function save_wx_purchase(){
        $map['purchaseid'] = I('post.id');
           $data['purchaseame'] =I('post.username');
           $data['isactive'] =I('post.in_or_out');
           $data['lasttime'] =I('post.end_time');
           $data['remark'] =I('post.remark');
           $data['operationuser'] = $_SESSION['admin_id'];
           $data['createtime'] = date('Y-m-d H:i:s');
            $exe_scriptstr = "<script>
                    setTimeout(function(){
                        var win=    art.dialog.opener;
                                    win._reload_currentpage_datalist('load_tb_div');
                                    art.dialog.close();
                    },1000);
                    
               </script>";
          

           $res = D('wx_purchase')->where($map)->save($data);
                
           if($res != flase){
            
                //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
                $this->success('操作成功！' . $exe_scriptstr);
            }else{
            
                //添加成功后，输出文本，把js脚本一起输出，前台只要html到某个div里就能够执行js
                $this->error('操作失败！' . $exe_scriptstr); 
            }
           $this->display();
  

}
  
       public function delete_wx_purchase(){
         if(IS_GET){
            $map['purchaseid'] = I('get.id');
            $row = D('wx_purchase')->where($map)->delete();
            if($row != flase){
                $this->success("删除成功") ;
            }else{
                $this->error("删除失败") ;
            }

         }

    }





//采购单审核
  
    public function add_approval(){
        $purchaseame = isset($_GET['purchaseame'])?$_GET['purchaseame']:"";
        $offerid = isset($_GET['offerid'])?$_GET['offerid']:"";
        $this->assign('purchaseame',$purchaseame);
        $this->assign('offerid',$offerid);
        $this->display();
    }


    public function add_approvalList(){


       $_listrows = I('request.verypageshowcount', '', 'trim');

        //$_where['transaction_type'] = 1;
        
    /*  $is_vip = I('request.is_vip',-1,'intval');
        if( $is_vip != -1){
            $_where['is_vip']=$is_vip;
        }
        */
        $keywords = I('request.keywords','','trim');
        if(!empty($keywords)){
            $_where['purchaseame|linkname']=array('like',"%{$keywords}%");
        }
        
        $start_time = I('request.start_time','','trim');
        $end_time = I('request.end_time','','trim');

        //采购单审批
         //$purchaseame =I('request.purchaseame');
         $offerid =I('request.offerid');
        $str='';
        if(!empty($offerid)){
           $str.=' and a.offerid ="'.$offerid .'"';
        }
        if(!empty($start_time)){
            $str.=' and a.createtime >= '.strtotime($start_time);
        }
        if(!empty($end_time)){
            $str.=' and a.createtime <= '.strtotime($end_time);
        }
        $str.="and a.ishandle=0";
        $str = ltrim(trim($str),'and');
        if(!empty($str)){
            $_where['_string']=$str;
        }
        $where_order['where'] = $_where;
        /*$where_order['order'] = ' last_transaction_time desc ';*/
        $where_order['listrows'] = $_listrows;
        $where_order['order']="createtime DESC";
        $where_order["id"]="load_tb_div";
        $where_order["field"]="a.*,b.code,b.offer_number,b.actual_number,b.offer_price,b.sendtime,b.isbatch,b.iscomfirm,c.purchaseame,d.linkname,e.goodsname";
        $where_order['alias']="a";
        $where_order["join"] =array('left join '.$this->dbprefix.'wx_offerlist b on a.offerid=b.offerid',' left join '.$this->dbprefix.'wx_purchase c on a.purchaseid=c.purchaseid',' left join '.$this->dbprefix.'wx_supplier d on a.sp_id=d.sp_id',' left join '.$this->dbprefix.'wx_purchaselist e on b.listid=e.listid');
        $_datalist = $this->_getListsFromModel('wx_offer', $where_order);
        $this->assign('_datalist', $_datalist);
        $this->display(); 

    }

 //审核报价单  
 public function save_approvalList(){
     $db = M();
     //$db2=M('wx_offer');
     $json =  $_POST['list'];
     $data = json_decode($json,true);
     $ret=array('staute'=>'error','msg'=>"保存失败");
     $time =  date('Y-m-d H:i:s',strtotime(" +16 h"));
     $arysqlupd = array();
     $arysqlupd2 =array();
    $aryofferid = array();
    $aryspid = array();
     foreach ($data as $k => $v) {
          $sqlupd="update ".$this->dbprefix."wx_offerlist set iscomfirm='1',operationuser=".UID.",actual_number='".$v['actual_number']."',offer_price='".$v['offer_price']."',createtime='".$time."' where code='".$v['idcode']."'";
                $arysqlupd[]=$sqlupd;
        //采取了报价单 获取采取的offerid
          $list = D('wx_offerlist')->field('offerid')->where("code='".$v['idcode']."'")->find();      
              $aryofferid[] = $list['offerid'];   
     }
    $aryofferid = array_unique($aryofferid);

       for ($i=0; $i < count($aryofferid) ; $i++) { 
         //修改主表的 isactive =1  设置为有效
           $sqlupd2="update ".$this->dbprefix."wx_offer set isactive='1',ishandle='1' ,`check` = '3',operationuser=".UID.",createtime='".$time."' where offerid='".$aryofferid[$i]."'";
                $arysqlupd2[]=$sqlupd2;
       }
      $db->startTrans(); //启动事务
      //从表更新
     if(count($arysqlupd)>0){
         foreach ($arysqlupd as $k=>$sql){
            if(empty($sql))continue;
            $retupd=$db->table('wx_offerlist')->execute($sql);
            //如果失败就退出循环，失败
            if(!$retupd){
                break;  
              }
             }
     }

   //主表更新
     if(count($arysqlupd2)>0){
         foreach ($arysqlupd2 as $k2=>$sql2){
            if(empty($sql2))continue;
            $retupd2=$db->table('wx_offer')->execute($sql2);
            //如果失败就退出循环，失败
            if(!$retupd2){
                break;  
              }
             }
     }

    
      if($retupd &&$retupd2){
            $db->commit();
             $ret=array("staute"=>"success","msg"=>"报价单审核成功");
        
                $data = array();
                 $mobile =D('wx_offer')->field('b.moblie')->alias('a')->join(" left join ".$this->dbprefix."wx_supplier b on a.sp_id= b.sp_id")->where('a.offerid ="'.$aryofferid[0].'"')->find();
                     $data['mobile'] = $mobile['moblie'];
                    // $data['mobile'] = "0480005462";
                      $url = C("WEBURL").'/wx.php/Offer/user_offer?offerid='.$aryofferid[0];
                      $data['content'] = "我们的管理员已经审核了您的报价单，请点击该连接查看(".$url.")，或者到网页51M个人中心查看！请尽快上传发票！";
                    
                     //请求mobile/smsmessage_au.php
                     $url=C("WEBURL")."/mobile/smsmessage_au.php?act=purchase_message";
                     //添加个参数区分需不需要构建session
                    file_put_contents('log.txt', '\r\n'.date('Y-m-d H:i:s').$data['mobile'].$data['content'],FILE_APPEND);// 这个函数支持版本(PHP 5) 

                     $result= $this->http_request($url,$data);
                     if($result=="" ||empty($result)){
                         $ret=array("staute"=>"1","msg"=>"短信发送失败!");
                         $this->ajaxReturn($ret);
                     }
                    echo $result;
                    exit;
          
        }else{
            $db->rollback();
             $ret=array("staute"=>"error","msg"=>"保存数据失败");
             $this->ajaxReturn($ret);
             exit;
        }
 }




    public  function selection_of_goods_list(){

        $id=I("post.id"); 

        $id= isset($id)?$id:'';
        $id =empty($id)?'':$id; 
        $sort=M("wx_purchase")->field("purchaseid,purchaseame")->select(); 
        $this->assign ( "purchase", $sort ); 
     if($id){
            $ls=D("wx_purchaselist")->alias("a")->field("a.*,c.purchaseame")->join(" left join ".$this->dbprefix."wx_purchase c on a.purchaseid= c.purchaseid")->where("a.purchaseid='$id'")->order("a.createtime desc")->select();
     }
        $this->assign('purchaselist',$ls);
        $this->assign("purchaseid",$id);

        $this->display();

    }



    public function update_wx_purchaselist(){
        $ret=array('staute'=>'error','msg'=>"保存失败");
        $purchase=I("purchase");
        $postdata=I("json");
        
        if(empty($purchase)||empty($postdata)){
            $ret=array('staute'=>'error','msg'=>"传输参数错误");
            $this->ajaxReturn ($ret);
            exit;
        } 
        
        $json = json_decode($postdata,true); 
        if(!is_array($json)){
            $ret=array('staute'=>'error','msg'=>"特价商品信息错误");
            $this->ajaxReturn ($ret);
            exit;
        }
        
        //对数据进行处理
         $sl=M("wx_purchaselist");
         $where['purchaseid'] = $purchase;
         $dblist= $sl->where($where)->select(); //数据库当前主题存在的记录信息;
         
         $aryadd=$arydel=$aryupd=array();
         //提交数据 是否在数据库中存在，存在更新否则增加
         foreach($json as $k=>$v){ 
            $flg=0;
            foreach ($dblist as $key=>$o){ 
              if($v["listid"]==$o['listid'] && $v["purchaseid"]==$o['purchaseid']  && $v["goodsid"]==$o['goodsid']){
                  $aryupd[]=$v;     
                  $flg=1;
                  break;
              }
            }
           if($flg==0){
                $v["listid"]=$listid;
                $aryadd[]=$v;
           }
         }
         
         //在数据库里存在，但是提交的数据不存在，删除数据
         foreach ($dblist as $key=>$o){
            $bl=0;
            foreach($json as $k=>$v){
              if($v["listid"]==$o['listid'] && $v["purchaseid"]==$o['purchaseid']&& $v["goodsid"]==$o['goodsid']){ 
                    $bl=1;
                    break;
                }
            }
            if($bl==0){
                $arydel[]=$o;
            }
         }
          
         $sqladd=$sqlupd=$sqldel="";
         $arysqlupd=array();  
         $time=date("Y-m-d H:i:s");
         

 
         //构建插入数据语句
         if(count($aryadd)>0){
            $sqlval=""; 
            foreach ($aryadd as $k=>$v){
                $listid=getGuid();//创建guid值
                $sqlval.=((empty($sqlval)?"":",")."('$listid','$purchase','".$v['goodsid']."','".$v['goodsname']."','".$v['unit']."','".$v['number']."','".$v['price']."',".UID.",'$time')");
            }
            $sqladd=" INSERT INTO  ".$this->dbprefix."wx_purchaselist(`listid`,`purchaseid`,`goodsid`,`goodsname`,`unit`,`number`,`price`,`operationuser`,`createtime`) values ".$sqlval;
         }
         
         //构建更新数据语句
         if(count($aryupd)>0){  
            foreach ($aryupd as $k=>$v){
                $sqlupd="update ".$this->dbprefix."wx_purchaselist set purchaseid='$purchase',goodsid='".$v['goodsid']."',goodsname='".$v['goodsname']."',unit='".$v['unit']."',number='".$v['number']."',price='".$v['price']."',operationuser='".UID."',createtime='".$time."' where listid='".$v['listid']."'";
                $arysqlupd[]=$sqlupd;
            } 
         }
        
         //构建删除数据语句
         if(count($arydel)>0){
            $sqlval="";
            foreach ($aryupd as $k=>$v){
                $sqlval.=((empty($sqlval)?"":",").$v['listid']);
            }
            if(!empty($sqlval))
               $sqldel="delete ".$this->dbprefix."wx_purchaselist where FIND_IN_SET(listid,'".$sqlval."')";
         }
         
         $db=M("wx_purchaselist");
         $retadd=$retupd= $retdel=1; //默认是成功状态
         
         $db->startTrans(); //启动事务
         
         if($sqladd){
            $retadd=$db->execute($sqladd);
         } 
         
         if(count($arysqlupd)>0){
             foreach ($arysqlupd as $k=>$sql){
                if(empty($sql))continue;
                $retupd=$db->execute($sql);
                //如果失败就退出循环，失败
                if(!$retupd){
                    break;  
                }
             }
         }
         
         if($sqldel){
            $retdel=$db->execute($sqldel);
         }
         
         if($retadd && $retupd && $retdel){
            $db->commit();
            $ret=array('staute'=>'success','msg'=>"保存数据成功");
         }
         else {
            $db->rollback();
            $ret=array('staute'=>'error','msg'=>"保存数据失败");
         }  
        $this->ajaxReturn($ret);
    }

    public function delete_wx_purchaselist(){
     if(IS_GET){
        $map['listid'] = I('get.id');
        $row = D('wx_purchaselist')->where($map)->delete();
        if($row != flase){
            $this->success("删除成功") ;
        }else{
            $this->error("删除失败") ;
        }

     }

    }


            //HTTP请求（支持HTTP/HTTPS，支持GET/POST）
    function http_request($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}


?>
